﻿using System;
using System.Web;
using EOSCRM.Linq.Audit;

namespace EOSCRM.Domain
{
    public partial class EOSCRMDataContext : EOSCRM.Linq.Audit.LinqToSql.AuditableDataContext
    {
        protected override void InsertAuditRecordToDatabase(EntityAuditRecord record)
        {
            var userLog = HttpContext.Current.Session["_EL_USER"] as UserLog;
            if (userLog == null) return;
            
            var audit = new AuditRecord
            {
                Action = (byte)record.Action,
                AuditDate = DateTime.Now,
                AssociationTable = record.AssociationTable,
                AssociationTableKey = record.AssociationTableKey,
                EntityTable = record.EntityTable,
                EntityTableKey = record.EntityTableKey,
                LogId = userLog.Id,
                UserName = userLog.MANV
            };


            foreach (var av in record.ModifiedProperties)
            {
                var field = new AuditRecordField { MemberName = av.MemberName, OldValue = av.OldValue, NewValue = av.NewValue };

                audit.AuditRecordFields.Add(field);
            }

            AuditRecords.InsertOnSubmit(audit);
        }

        protected override void DefaultAuditDefinitions()
        {
            this.NHANVIENs.Audit();
        }
    }
}
